#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
    unmanic.database.py

    Written by:               Josh.5 <jsunnex@gmail.com>
    Date:                     14 Aug 2021, (12:03 PM)

    Copyright:
           Copyright (C) Josh Sunnex - All Rights Reserved

           Permission is hereby granted, free of charge, to any person obtaining a copy
           of this software and associated documentation files (the "Software"), to deal
           in the Software without restriction, including without limitation the rights
           to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
           copies of the Software, and to permit persons to whom the Software is
           furnished to do so, subject to the following conditions:

           The above copyright notice and this permission notice shall be included in all
           copies or substantial portions of the Software.

           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
           EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
           MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
           IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
           DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
           OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
           OR OTHER DEALINGS IN THE SOFTWARE.

"""
import importlib
import inspect
import os
import sys

from peewee import Model, SqliteDatabase, Field
from peewee_migrate import Migrator, Router

from unmanic.libs.logs import UnmanicLogging
from unmanic.libs.unmodels.lib import BaseModel


class Migrations(object):
    """
    Migrations

    Handle all migrations during application start.
    """

    database = None

    def __init__(self, config):
        self.logger = UnmanicLogging.get_logger(name=__class__.__name__)

        # Based on configuration, select database to connect to.
        if config['TYPE'] == 'SQLITE':
            # Create SQLite directory if not exists
            db_file_directory = os.path.dirname(config['FILE'])
            if not os.path.exists(db_file_directory):
                os.makedirs(db_file_directory)
            self.database = SqliteDatabase(config['FILE'])

            self.router = Router(database=self.database,
                                 migrate_table='migratehistory_{}'.format(config.get('MIGRATIONS_HISTORY_VERSION')),
                                 migrate_dir=config.get('MIGRATIONS_DIR'),
                                 logger=self.logger)

            self.migrator = Migrator(self.database)

    def __run_all_migrations(self):
        """
        Run all new migrations.
        Migrations that have already been run will be ignored.

        :return:
        """
        self.router.run()

    def update_schema(self):
        """
        Updates the Unmanic database schema.

        Newly added tables/models and columns/fields will be automatically generated by this function.
        This way we do not need to create a migration script unless we:
            - rename a column/field
            - delete a column/field
            - delete a table/model

        :return:
        """
        # Fetch all model classes
        discovered_models = inspect.getmembers(sys.modules["unmanic.libs.unmodels"], inspect.isclass)
        all_models = [tup[1] for tup in discovered_models]

        # Start by creating all models
        self.logger.info("Initialising database tables")
        try:
            with self.database.transaction():
                for model in all_models:
                    self.migrator.create_table(model)
                self.migrator()
        except Exception:
            self.database.rollback()
            self.logger.exception("Initialising tables failed")
            raise

        # Migrations will only be used for removing obsolete columns
        self.__run_all_migrations()

        # Newly added fields can be auto added with this function... no need for a migration script
        # Ensure all files are also present for each of the model classes
        self.logger.info("Updating database fields")
        for model in all_models:
            if issubclass(model, BaseModel):
                # Fetch all peewee fields for the model class
                # https://stackoverflow.com/questions/22573558/peewee-determining-meta-data-about-model-at-run-time
                fields = model._meta.fields
                # loop over the fields and ensure each on exists in the table
                field_keys = [f for f in fields]
                for fk in field_keys:
                    field = fields.get(fk)
                    if isinstance(field, Field):
                        if not any(f for f in self.database.get_columns(model._meta.name) if f.name == field.name):
                            # Field does not exist in DB table
                            self.logger.info("Adding missing column")
                            try:
                                with self.database.transaction():
                                    self.migrator.add_columns(model, **{field.name: field})
                                    self.migrator()
                            except Exception:
                                self.database.rollback()
                                self.logger.exception("Update failed")
                                raise